/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.serialize;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @author creativor
 * 
 */
abstract class SerializableType<T> {
	private final byte type;

	protected SerializableType(final byte type) {
		this.type = type;
	}

	/**
	 * @return the type
	 */
	public final byte getType() {
		return type;
	}

	/**
	 * 
	 * @param dis
	 * @return
	 * @throws SerializeFormatException
	 * @throws UnsupportedTypeException
	 */
	abstract T read(final DataInput dis) throws SerializeFormatException, IOException,
			UnsupportedTypeException;

	abstract Object readArray(DataInput dis, int arrayLength) throws SerializeFormatException,
			IOException;

	/**
	 * By default, this method read EOF signal only.
	 * 
	 * @param dis
	 * @param obj
	 * @throws SerializeFormatException
	 * @throws IOException
	 */
	protected void readFields(final DataInput dis, final Object obj)
			throws SerializeFormatException, IOException {
		final short type = dis.readShort();
		if (type != Constants.EOF)
			throw new SerializeFormatException("expected EOF " + Constants.EOF + " but " + type);
	}

	/**
	 * @param dos
	 * @param value
	 * @throws UnsupportedTypeException
	 */
	abstract void write(final DataOutput dos, final T value) throws IOException,
			UnsupportedTypeException;

	/**
	 * @param dos
	 * @param array
	 * @throws IOException
	 * @throws UnsupportedTypeException
	 */
	abstract void writeArray(final DataOutput dos, final Object array) throws IOException,
			UnsupportedTypeException;

	/**
	 * By default, this method write EOF signal only.
	 * 
	 * @param dos
	 * @param obj
	 * @throws IOException
	 */
	protected void writeFields(final DataOutput dos, final Object obj) throws IOException {
		dos.writeShort(Constants.EOF);
	}
}